from django import forms
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator

from app01.utils.form.bootsrapform import BootStrapForm, BootStrapModelForm
from app01 import models
from app01.utils.cos import check_file

class FileFolderModelForm(BootStrapModelForm):
    class Meta:
        model = models.FileRepository
        fields = ['name']
        widgets = {
            'name': forms.TextInput(attrs={'autocomplete': 'off'})
        }
    
    def __init__(self, request, parent_object, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request
        self.parent_object = parent_object
    def clean_name(self):
        # 判断当前文件夹是否存在
        name = self.cleaned_data.get('name')

        queryset = models.FileRepository.objects.filter(name=name, project=self.request.tracer.project)
        if self.parent_object:
           exists = queryset.filter(parent=self.parent_object).exists()
        else:
           exists = queryset.filter(parent__isnull=True).exists()

        if exists:
            raise ValidationError('文件夹已存在')
        return name
    
class FileModelForm(forms.ModelForm):
    etag = forms.CharField(label="Etag")
    class Meta:
        model = models.FileRepository
        exclude = ['project', 'file_type', 'update_user', 'update_datetime']

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_file_path(self):

        return "https://{}".format(self.cleaned_data.get('file_path'))
    
    # def clean(self):
    #     etag = self.cleaned_data['etag']
    #     key = self.cleaned_data['key']
    #     file_size = self.cleaned_data['file_size']

    #     if not etag or not key:
    #         return self.cleaned_data 
        
    #     # cos效验文件示否合法
    #     from qcloud_cos.cos_exception import CosServiceError
    #     try:
    #         result = check_file(self.request.tracer.project.bucket, self.request.tracer.project.region, key)
    #         print(result)
    #     except CosServiceError as e:
    #         self.add_error('key', '文件不存在')
    #         return self.cleaned_data
        
    #     cos_etag = result.get('etag')
    #     if etag != cos_etag:
    #         self.add_error('etag', 'Etag不匹配')
        
    #     cos_length = result.get('Content-Length')
    #     if int(cos_length) != file_size:
    #         self.add_error('size', '文件大小错误')

        return self.cleaned_data
        
        
